package com.nn.smart.bus.commons.tools.utils;

import com.nn.smart.bus.commons.tools.constant.NumConstant;
import org.apache.commons.lang3.StringUtils;

import javax.imageio.ImageIO;
import java.awt.image.BufferedImage;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;

/**
 * @author nanning
 * @date
 */
public class FileUtils {


    /**
     * File文件转为byte[]
     *
     * @param file
     * @return byte[]
     * @author nanning
     * @date 2019/9/19 15:56
     */
    public static byte[] fileToByteArray(File file) {
        try {
            //获取输入流
            FileInputStream fis = new FileInputStream(file);
            //新的 byte 数组输出流，缓冲区容量1024byte
            ByteArrayOutputStream bos = new ByteArrayOutputStream(1024);
            //缓存
            byte[] b = new byte[1024];
            int n;
            while ((n = fis.read(b)) != NumConstant.ONE_NEG) {
                bos.write(b, NumConstant.ZERO, n);
            }
            fis.close();
            //改变为byte[]
            byte[] data = bos.toByteArray();
            bos.close();
            return data;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

    /**
     * BufferedImage文件转为byte[]
     *
     * @param bImage     图片
     * @param formatName 格式 e.g. png
     * @return byte[]
     * @author nanning
     * @date 2020/8/7 13:30
     */
    public static byte[] imageToBytes(BufferedImage bImage, String formatName) {
        if (null == bImage || StringUtils.isBlank(formatName)) {
            return null;
        }
        ByteArrayOutputStream out = new ByteArrayOutputStream();
        try {
            ImageIO.write(bImage, formatName, out);
        } catch (IOException e) {
            //log.error(e.getMessage());
        }
        return out.toByteArray();
    }

}
